package com.zmn.mcc.dubbo.impl.staff.dingtalk;

import com.taobao.api.ApiException;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.business.interfaces.staff.dingtalk.DingTalkService;
import com.zmn.mcc.common.dto.dingtalk.SendImageMessage;
import com.zmn.mcc.common.dto.dingtalk.SendImageMessageResult;
import com.zmn.mcc.dubbo.dto.DubboConsts;
import com.zmn.mcc.common.dto.dingtalk.RobotSendGroupMessage;
import com.zmn.mcc.dubbo.interfaces.staff.dingtalk.DingTalkRemoteService;
import com.zmn.mcc.model.entity.staff.McStaff;
import com.zmn.mcc.model.entity.staff.StaffIdAndDTalkId;
import com.zmn.mcc.model.entity.staff.dingtalk.DingTalkIdAndMediaId;
import com.zmn.mcc.services.interfaces.staff.StaffService;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 员工发送钉钉通知消息
 *
 * @author tanghongjun
 * @since 2021年3月9日17:50:00
 */
@Service(version = DubboConsts.INTERFACE_VERSION, validation = "true")
public class DingTalkRemoteServiceImpl implements DingTalkRemoteService {
    private final Logger logger = LoggerFactory.getLogger(DingTalkRemoteServiceImpl.class);

    @Resource
    DingTalkService dingTalkService;
    @Resource
    StaffService staffService;

    @Override
    public ResponseDTO<Boolean> sendDingTalkWorkRecord(String mobile, String content) {
        try {

            List<McStaff> mcStaffs = staffService.listByMoblieAndDTalkIdIsNotNull(mobile);
            if (CollectionUtil.isNullOrEmpty(mcStaffs) || mcStaffs.size() != 1) {
                logger.info(String.format("发送钉钉消息失败，userId: {}, content: {}", mobile, content));
                return ResponseDTO.fail("发送钉钉消息失败,员工不存在钉钉ID或有多个钉钉ID");
            }

            return dingTalkService.sendDingTalkWorkRecord(mcStaffs.get(0).getDTalkId(), content);
        } catch (ApiException e) {
            logger.info(String.format("发送钉钉消息失败，userId: {}, content: {}", mobile, content));
            return ResponseDTO.fail(e.getMessage());
        }

    }

    /**
     * 通过机器人向指定群发送消息
     *
     * @param message 钉钉机器人发送群消息对象
     * @return  true 发送成功 false 发送失败
     * @author xujie
     * @since 2021/03/22
     */
    @Override
    public ResponseDTO<Boolean> sendMessageToGroupByRobot(RobotSendGroupMessage message) {

        try {
            return dingTalkService.sendMessageToGroupByRobot(message);
        } catch (Exception e) {
            logger.info(String.format("钉钉机器人发送群消息失败, content: {}", message.getContent()));
            return ResponseDTO.success(false, e.getMessage());
        }
    }

    /**
     * 发送图片消息
     *
     * @param imgMsgList 发送图片消息对象
     * @return 发送图片消息结果
     * @author xujie
     * @since 2021/04/28
     */
    @Override
    public ResponseDTO<List<SendImageMessageResult>> sendImageMessage(List<SendImageMessage> imgMsgList) {

        Map<Integer, String> staffMap = imgMsgList.stream().collect(Collectors.toMap(SendImageMessage::getStaffId, SendImageMessage::getMediaId, (e1, e2) -> e2));
        List<Integer> staffIdList = new ArrayList<>(staffMap.keySet());
        List<StaffIdAndDTalkId> staffIdAndTalkIdList = staffService.listStaffIdAndDTalkIdByStaffIdList(staffIdList);
        Map<Integer, String> staffIdAndTalkIdMap = staffIdAndTalkIdList.stream().collect(Collectors.toMap(StaffIdAndDTalkId::getStaffId, StaffIdAndDTalkId::getDTalkId, (e1, e2) -> e2));
        List<DingTalkIdAndMediaId> dingTalkIdAndMediaIdList = new ArrayList<>(staffIdAndTalkIdMap.size());
        staffIdList.forEach(staffId -> {
            String dTalkId = staffIdAndTalkIdMap.get(staffId);
            String mediaId = staffMap.get(staffId);
            if (StringUtil.isNotBlank(dTalkId) && StringUtil.isNotBlank(mediaId)) {
                dingTalkIdAndMediaIdList.add(DingTalkIdAndMediaId.builder().staffId(staffId).dTalkId(dTalkId).mediaId(mediaId).build());
            }
        });
        return dingTalkService.sendImageMessage(dingTalkIdAndMediaIdList);
    }

    /**
     * 获取钉钉AccessToken
     *
     * @return AccessToken
     * @author xujie
     * @since 2021/04/29
     */
    @Override
    public ResponseDTO<String> getDingTalkAccessToken() {

        try {
            String accessToken = dingTalkService.getDingTalkAccessToken();
            return ResponseDTO.success(accessToken, "获取cg");
        } catch (ApiException e) {
            logger.error("获取钉钉AccessToken异常：{}", e.getMessage(), e);
            return ResponseDTO.fail("获取钉钉AccessToken异常：" + e.getMessage());
        }
    }
}
